package com.qfedu.openplateform.gateway.filter;

import com.qfedu.openplateform.common.entity.LoggerBean;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

/**
 *  GlobalFilter , Ordered
 * @author lileijian
 * @create 2021-12-05 0:38
 */
public class TokenFilter implements HandlerInterceptor {

    // 就是为每一个请求的线程 创建一个副本 变量,其他线程看不到
    private ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override  // 请求之前 进行拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 记录请求路径 请求参数  请求的ip   ，响应  时长
        threadLocal.set(new Date());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override// 整个请求响应 完成后
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoggerBean loggerBean = new LoggerBean();
        Date responeDate = new Date();
        Date startTime = threadLocal.get();

        loggerBean.setResponseTime(responeDate);//设置响应时间
        loggerBean.setReveivceTime(startTime);
        loggerBean.setApp_key(request.getParameter("app_key"));
        loggerBean.setApiName(request.getParameter("method"));
        loggerBean.setRemoteIp(request.getRemoteAddr());


        loggerBean.setTotalTime(responeDate.getTime() - startTime.getTime());//设置总时间
        try {
            loggerBean.setServerIp(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        loggerBean.setContent(request.getQueryString());

        System.out.println("loggerBean:"+loggerBean);


        // 响应后的时间
        long currentTime = System.currentTimeMillis();


        loggerBean.setRemoteIp(request.getRemoteAddr().toString());
        loggerBean.setServerIp(request.getServerName());





    }
}
